"""Tag Management API - 标签管理接口."""

from __future__ import annotations

import os
from typing import List, Any

from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session

from ...deps import get_db, get_current_user
from ....models.user import User
from ....repositories.tag_repository import TagRepository
from ....repositories.lead_tag_repository import LeadTagRepository
from ....schemas.tag import (
    TagCreate,
    TagUpdate,
    TagResponse,
    TagStatistics,
)
from ....services.tag_service import TagService

router = APIRouter()


def get_tag_service(db: Session = Depends(get_db)) -> TagService:
    """获取TagService依赖."""
    tag_repo = TagRepository(db)
    lead_tag_repo = LeadTagRepository(db)

    # 获取API密钥（可选，用于AI增强）
    qwen_key = os.getenv("QWEN_API_KEY")
    hunyuan_id = os.getenv("HUNYUAN_SECRET_ID")
    hunyuan_key = os.getenv("HUNYUAN_SECRET_KEY")

    return TagService(
        tag_repo=tag_repo,
        lead_tag_repo=lead_tag_repo,
        qwen_api_key=qwen_key,
        hunyuan_secret_id=hunyuan_id,
        hunyuan_secret_key=hunyuan_key,
    )


# ========== Tag CRUD接口 ==========


@router.post("/", response_model=TagResponse, status_code=201)
def create_tag(
    tag_data: TagCreate,
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> TagResponse:
    """创建新标签（仅管理员）."""
    # 检查名称是否已存在
    existing = tag_service.get_tag_by_name(tag_data.name)
    if existing:
        raise HTTPException(status_code=400, detail=f"标签名称 '{tag_data.name}' 已存在")

    tag = tag_service.create_tag(tag_data)
    # get_db会自动commit和refresh
    return tag  # type: ignore[return-value]


@router.get("/", response_model=List[TagResponse])
def list_tags(
    category: str | None = Query(
        None, description="按分类过滤: facility/environment/special/custom"
    ),
    level: int | None = Query(None, ge=1, le=3, description="按优先级过滤: 1-3星"),
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(100, ge=1, le=200, description="返回记录数"),
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> List[TagResponse]:
    """获取标签列表（支持分类和优先级过滤）."""
    tags = tag_service.list_tags(category=category, level=level, skip=skip, limit=limit)
    return tags  # type: ignore[return-value]


@router.get("/popular", response_model=List[TagResponse])
def get_popular_tags(
    limit: int = Query(20, ge=1, le=50, description="返回热门标签数"),
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> List[TagResponse]:
    """获取热门标签（按使用次数排序）."""
    tags = tag_service.get_popular_tags(limit)
    return tags  # type: ignore[return-value]


@router.get("/statistics", response_model=TagStatistics)
def get_tag_statistics(
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> TagStatistics:
    """获取标签统计信息."""
    stats = tag_service.get_statistics()
    return stats  # type: ignore[return-value]


@router.get("/{tag_id}", response_model=TagResponse)
def get_tag(
    tag_id: int,
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> TagResponse:
    """获取标签详情."""
    tag = tag_service.get_tag(tag_id)
    if not tag:
        raise HTTPException(status_code=404, detail="标签不存在")
    return tag  # type: ignore[return-value]


@router.patch("/{tag_id}", response_model=TagResponse)
def update_tag(
    tag_id: int,
    tag_data: TagUpdate,
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> TagResponse:
    """更新标签（仅管理员）."""
    # 检查名称冲突
    if tag_data.name:
        existing = tag_service.get_tag_by_name(tag_data.name)
        if existing and existing.id != tag_id:
            raise HTTPException(status_code=400, detail=f"标签名称 '{tag_data.name}' 已存在")

    tag = tag_service.update_tag(tag_id, tag_data)
    if not tag:
        raise HTTPException(status_code=404, detail="标签不存在")
    # get_db会自动commit
    return tag  # type: ignore[return-value]


@router.delete("/{tag_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_tag(
    tag_id: int,
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> Response:
    """删除标签（软删除，设置is_active=False）（仅管理员）."""
    success = tag_service.delete_tag(tag_id)
    if not success:
        raise HTTPException(status_code=404, detail="标签不存在")
    # get_db会自动commit
    # 204状态码不需要返回内容
    return Response(status_code=status.HTTP_204_NO_CONTENT)


# ========== 标签匹配接口 ==========


@router.post("/match", response_model=List[dict[str, Any]])
def match_tags_from_text(
    text: str = Query(..., min_length=2, description="要匹配的文本（备注）"),
    max_tags: int = Query(4, ge=1, le=10, description="最多返回标签数"),
    tag_service: TagService = Depends(get_tag_service),
    current_user: User = Depends(get_current_user),
) -> List[dict[str, Any]]:
    """从文本中匹配标签（混合引擎：规则80% + AI 20%）.

    示例请求:
    ```
    POST /api/v1/tags/match?text=需要近地铁的房子，采光要好&max_tags=4
    ```

    返回格式:
    ```json
    [
        {
            "tag_id": 1,
            "tag_name": "近地铁",
            "confidence": 0.95,
            "level": 3,
            "source": "ai"
        },
        {
            "tag_id": 5,
            "tag_name": "采光好",
            "confidence": 0.90,
            "level": 2,
            "source": "rule"
        }
    ]
    ```
    """
    matched_tags = tag_service.match_tags_from_text(text, max_tags)
    return matched_tags
